package com.bjsdzk.common.utils;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class BaiduUtil {
    private final static Logger logger = LoggerFactory.getLogger(BaiduUtil.class);

    final static String CREATE_API = "https://dwz.cn/admin/v2/create";
    final static String TOKEN = "34aad3ab367591934dd089e514ad784d";

    /**
     * 创建短网址
     *
     * @param longUrl 长网址：即原网址
     *                termOfValidity
     *                有效期：1-year或long-term
     * @return 成功：短网址
     * 失败：返回空字符串
     */
    public static String createShortUrl(String longUrl, String termOfValidity) {
//        String params = "{\"Url\":\"" + longUrl + "\",\"TermOfValidity\":\""+termOfValidity+"\"}";
        String params = "{\"Url\":\"" + longUrl + "\",\"TermOfValidity\":\"1-year\"}";

        BufferedReader reader = null;
        try {
            // 创建连接
            URL url = new URL(CREATE_API);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Token", TOKEN); // 设置发送数据的格式");

            // 发起请求
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); // utf-8编码
            out.append(params);
            out.flush();
            out.close();

            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            // 抽取生成短网址
            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject.getInteger("Code") == 0) {
                return jsonObject.getString("ShortUrl");
            } else {
                logger.info(jsonObject.getString("ErrMsg"));
            }

            return "网络错误21066";
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
        return "网络错误21077";
    }

    public static void main(String[] args) {
//        String res = createShortUrl("http://support.bjsdzk.com/app/download?type=fault&companyId=17d5d6d5-439f-483f-9065-93b8b508ff76", null);
        Map<String, Double> test = getPoint("太阳宫七圣中街12号院-1号楼");
        for (Map.Entry<String, Double> entry : test.entrySet()) {
            System.out.println(entry.getKey() + "---" + entry.getValue());
        }
    }

    public static Map<String, Double> getPoint(String address) {
        String ak = "t3H9pA3wUYuU9jUAcfXzdtcEmOSoOegr";
        String url = "http://api.map.baidu.com/geocoder/v2/?output=json&address=" + address + "&ak=" + ak;

        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = HttpClients.createDefault();

        Map<String, Double> resMap = new HashMap<>();
        double lat = 0;
        double lng = 0;
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                if (!StringUtils.isEmpty(strResult)) {
                    JSONObject json = JSON.parseObject(strResult);
                    if (json != null && json.getIntValue("status") == 0) {
                        JSONObject pointJson = json.getJSONObject("result");
                        lat = pointJson.getJSONObject("location").getDoubleValue("lat");
                        lng = pointJson.getJSONObject("location").getDoubleValue("lng");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resMap.put("lat", lat);
        resMap.put("lng", lng);

        return resMap;
    }
}
